class SchedulesController < ApplicationController
  
  # GET /schedules
  # GET /schedules.xml
  def index
    # if user logged in (Don't worry about this case for now)
      # find all schedules of user
      # populate schedules tab with schedule names
      # display the most recent schedule
    # else
    @schedule = Schedule.find(:first, :conditions => {:id => session[:scheduleId]})
    @courses = []
    @lectures = []
    @discussions = []
    @labs = []
    @constraints = []

    # This special case should go away in the final product
    return if @schedule == nil
    # if self.current_user != nil
    #   mostRecentSchedule = current_user.getLatestSchedule
    #   if mostRecentSchedule == nil
    #     @schedule = schedule
    #   else
    #     @schedule = mostRecentSchedule
    #   end
    # else
    #   @schedule = schedule
    # end

    # Populate lectures, discussions, and labs
    @schedule.events.each do
      |event|
      courses = Course.find(:all, :conditions => {:id => event.course_id})
      if courses.size == 1
        @courses.push(courses[0])
        @lectures += courses[0].lectures
        @discussions += courses[0].discussions
        @labs += courses[0].labs
      end
    end
    
    @courses.uniq!
    @lectures.uniq!
    @discussions.uniq!
    @labs.uniq!
    @constraints.uniq!
 end
 
 def show
   begin
     @schedule = Schedule.find(params[:id])
   rescue
     return clear_schedule if params[:id] == 'clear_schedule'
     return save_schedule if params[:id] == 'save_schedule'
     return remove_course if params[:id] == 'remove_course'
     return copy_to_working_schedule if params[:id] == 'copy_to_working_schedule'
     return delete if params[:id] == 'delete'
     redirect_to :root
   end
   if @schedule
     if not logged_in? or @schedule.user != current_user
       redirect_to :root
     end
     @courses = []
     @lectures = []
     @discussions = []
     @labs = []
     @constraints = []
     @schedule.events.each do
       |event|
       courses = Course.find(:all, :conditions => {:id => event.course_id})
       if courses.size == 1
         @courses.push(courses[0])
         @lectures += courses[0].lectures
         @discussions += courses[0].discussions
         @labs += courses[0].labs
       end
     end

     # Remove duplications
     @courses.uniq!
     @lectures.uniq!
     @discussions.uniq!
     @labs.uniq!
   end
   render :template => 'schedules/index', :locals => {:interactive => false}
 end

  def addCourseCurrentSchedule
    schedule = Schedule.find(session[:scheduleId])
    event = Event.find(:first, :conditions => {:ccn => params[:ccn]})
    responseParams = {}
    responseParams['status'] = false
    if schedule and event
      toRemove = schedule.findAndRemoveSimilar(event)
      ccnsToRemove = toRemove.map{|event| event.ccn}
      schedule.events << Event.find(:first, :conditions => {:ccn => params[:ccn]})
      responseParams['status'] = true
      responseParams['toRemove'] = ccnsToRemove
    end
    render :text => responseParams.to_json
  end

  def removeCourseCurrentSchedule
    schedule = Schedule.find(session[:scheduleId])
    event = Event.find(:first, :conditions => {:ccn => params[:ccn]})
    if schedule and event
      schedule.events.delete(event)
      render :text => true
      return
    end
    render :text => false  
  end

  # generate a unique "id" for a commitment NOT to be put in the server
  def getACommitVal
    val = session['commit_id']
    if val == nil
      session['commit_id'] = 1000001
      return 1000000
    end
    session['commit_id'] = session['commit_id'] + 1
    return val
  end

  def save_schedule
    responseParams = {}
    responseParams['status']= false
    if self.current_user != nil
      schedule = Schedule.find(session[:scheduleId])
      newschedule = Schedule.create!()
      newschedule.events += schedule.events
      self.current_user.schedules << newschedule
      responseParams['status']= true
    end
#    render :text => responseParams.to_json
    redirect_to :action => :index
  end

  def clear_schedule
    Schedule.find(session[:scheduleId]).events.clear
    redirect_to :action => :index
  end

  def remove_course
    schedule = Schedule.find(session[:scheduleId])
    if schedule
      eventsToRemove = schedule.events.select { |event|
        event.course and event.course.id == params[:course_id].to_i
      }
      eventsToRemove.each do |event| schedule.events.delete(event) end
    end
    redirect_to :action => :index
  end

  def copy_to_working_schedule
    cur_schedule = Schedule.find(params[:schedule_id])
    responseParams = {}
    responseParams['status']= false
    if self.current_user != nil
      schedule = Schedule.find(session[:scheduleId])
      schedule.events.clear
      schedule.events += cur_schedule.events
      responseParams['status']= true
    end
#    render :text => responseParams.to_json
    redirect_to :action => :index
  end

  def delete
    to_delete = Schedule.find(params[:schedule_id])
    to_delete.destroy
    redirect_to :action => :index
  end

  def getNewCommitment
    responseId = ''
    if self.current_user != nil
      commit = Commitment.create!
      self.current_user.commitments << commit
      responseId = commit.id
    else
    responseId = getACommitVal
    end
    render :text => responseId
  end

  def getBool(str)
    str == "true"
  end

  def updateCommitment   
    responseParams = {}
    responseParams['status'] = true;
    theId = params['id']
    myId = theId[7, theId.length]
    myName = params['name']
    theStart = params['start']
    myStart = Time.parse(theStart)
    theEnd = params['end']
    myEnd = Time.parse(theEnd)
    isMo = getBool(params['Mo'])
    isTu = getBool(params['Tu'])
    isWe = getBool(params['We'])
    isTh = getBool(params['Th'])
    isFr = getBool(params['Fr'])
    isSa = getBool(params['Sa'])
    isSu = getBool(params['Su'])
    if myStart >= myEnd
      responseParams['status'] = false
      responseParams['error'] = 'Start Time must be before End Time!'
      render :text => responseParams.to_json
      return
    end
    if (!isMo and !isTu and !isWe and !isTh and !isFr and !isSa and !isSu)
      responseParams['status'] = false
      responseParams['error'] = 'Commitment must occur on some day of the week!'
      render :text => responseParams.to_json
      return
    end
    if self.current_user != nil
      Commitment.update(myId, myName, myStart, myEnd, isMo, isTu, isWe, isTh, isFr, isSa, isSu)
    end
    # No updating done if user not logged in
    render :text => responseParams.to_json
  end

  def removeCommitment
    theId = params['id']
    myId = theId[7, theId.length]
    if self.current_user != nil
      Commitment.delete(theId)
    end
    render :text => 'true'
  end
end
